package day021.tcp.demo7;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class UploadTask implements Runnable {
    private Socket server;
    private Logger LOGGER;
    private InputStream netInput;
    private FileOutputStream fos;
    private BufferedWriter bw;

    public UploadTask(Socket server, Logger LOGGER) {
        this.server = server;
        this.LOGGER = LOGGER;
    }

    @Override
    public void run() {
        try {
            netInput = server.getInputStream();
            String fileName = UUID.randomUUID().toString().replace("-", "");
            fos = new FileOutputStream("D:\\ideaProjects\\javase_code\\study-practice\\" +
                    "src\\day021\\tcp\\upload\\" + fileName + ".jpg");

            IOUtils.copy(netInput, fos);
            LOGGER.trace("文件上传成功！");

            bw = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
            bw.write("文件上传成功！");
            bw.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                netInput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
